﻿using ContactSMS.Commons.QueryParameters;
using ContactSMS.Commons.Responses;
using ContactSMS.Domain;
using ContactSMS.WebAPI.Common;
using ContactSMS.WebAPI.Controllers.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ContactSMS.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class MessageController : ControllerBase
    {
        private readonly IMessageRepository _messageRepository;
        private readonly TokenService _tokenService;

        public MessageController(IMessageRepository messageRepository, TokenService tokenService)
        {
            this._messageRepository = messageRepository;
            this._tokenService = tokenService;
        }

        [HttpGet]
        public async Task<IActionResult> GetMessage([FromQuery] MessageQueryParameters parameters, int page = 1, int pageSize = 10)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            ServiceResponse<bool> resp1 = new ServiceResponse<bool>();
            if (parameters.MessageSessionId == 0)
            {
                resp1.Success = false;
                resp1.Message = "会话id不能为空";
                return Ok(resp1);
            }
            try
            {
                var messages = await _messageRepository.GetMessageAsync(parameters, page, pageSize, parameters.MessageSessionId);
                var resp = new ServiceResponse<MessageSearchResponse>()
                {
                    Data = new MessageSearchResponse
                    {
                        list = messages.Message,
                        CurrentPage = page,
                        Pages = (int)messages.TotalPages
                    }
                };
                return Ok(resp);
            }
            catch (Exception ex)
            {
                ServiceResponse<bool> resp = new ServiceResponse<bool>();
                resp.Success = false;
                resp.Message = "暂无数据";
                return StatusCode(500, resp);
            }
        }

        [HttpDelete]
        [Route("{id:long}")]
        public async Task<IActionResult> DeleteById([FromRoute] long id)
        {
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            var result = await _messageRepository.DeleteMessageByIdAsync(id);
            if (result == false)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return NotFound(resp);
            }
            resp.Success = true;
            resp.Message = "删除成功";
            return Ok(resp);
        }

        [HttpPost]
        public async Task<IActionResult> DeleteByIds([FromBody] List<long> ids)
        {
            var userId = _tokenService.GetUserIdFromRequest(Request);
            if (userId == 0)
            {
                return Unauthorized("Invalid token.");
            }
            ServiceResponse<bool> resp = new ServiceResponse<bool>();
            if (ids == null || ids.Count == 0)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return BadRequest(resp);
            }
            var deletedMessages = await _messageRepository.DeleteMessageByIdsAsync(ids.ToArray());
            if (deletedMessages == false)
            {
                resp.Success = false;
                resp.Message = "删除失败";
                return NotFound(resp);
            }
            resp.Success = true;
            resp.Message = "删除成功";
            return Ok(resp);
        }
    }
}
